package com.bosssoft.trainee.nontax.common.eception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Luo Wenlong
 * @date 2022-06-26 14:49
 * @description:controller exception 统一异常处理类
 * @version: 1.0.0
 */
@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class ControllerExceptionHandler {
    @ExceptionHandler({Exception.class})
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error("sever error: " + e.getMessage());
        //详细打印每一句出错的问题
        for (StackTraceElement element : e.getStackTrace()) {
            log.error(element.toString());
        }
        //得到请求方式
        String xRequestedWith = request.getHeader("x-requested-with");
        //如果是异步请求，则返回统一处理数据给前端
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/plain;charset=utf-8");//普通文本，浏览器会自动转换为json格式
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            writer.write("sever error");
        } else {
            //如果不是，则直接返回错误页面，这个错误页面也是我自己定义的
            try {
                response.sendRedirect(request.getContextPath() + "/error");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
